import Emitter from '@multi-kit/emitter'
import { SerialPort } from 'serialport'
import { ReadlineParser } from '@serialport/parser-readline'

export default class SerialportServer extends Emitter {
  constructor({path, baudRate}) {
    super()
    this.port = new SerialPort({
      path, // 串口号，Windows 用 COMx，Linux/Mac 用 /dev/ttyUSBx
      baudRate // 波特率，根据设备要求设置
    })

    // 用换行符解析（可改为 BufferParser）
    this.parser = this.port;
    this.parser.on('data', (data) => {
      console.log('收到数据:', data)
      this._events['message'].forEach(event => {
        event(data)
      });
    })
  }

  send(message) {
    this.port.write(message)
  }

  sendAsync(data, { parser, acceptChecker }) {
    let hasAccept = false
    return new Promise((resolve, reject) => {
      if (typeof data === 'string') {
        data = Buffer.from(data)
      }
      const onMessage = (msg,) => {
        const message = parser(msg)

        if (acceptChecker(message)) {
          hasAccept = true
          this.off('message', onMessage)
          resolve(message)
        }
      }
      this.on('message', onMessage)
      const timer = setTimeout(() => {
        if (!hasAccept) {
          this.off('message', onMessage)
          reject(new Error('Timeout waiting for response'))
        }
        clearTimeout(timer)
      }, 400)

      this.port.write(data, (err) => {
        if (err) {
          // this.off('message', onMessage)
          reject(err)
        }
      })
    })
  }
}
